<?php

namespace app\controllers;

use yii\base\DynamicModel;
use yii\db\Exception;
use yii\validators\Validator;
use yii\web\HttpException;

/**
 * 参数验证示例
 */
class ValidateController extends BaseController
{
    public function actionIndex()
    {
        /**
         * 定义验证规则
         * 1.不能在同一行写多个验证规则
         */
        $rules = [
            //['kind', 'integer', 'in', 'range' => [1,2]],
            ['id', 'required', 'message' => 'ID不能为空', ],
            ['id', 'integer', 'message' => 'ID必须是整数', ],
            ['name', 'required', ],
            ['name', 'string', 'max' => 5, ],
            [['name', 'email'], 'string', 'max' => 128, ],
            ['email', 'email', 'message' => '邮箱格式不正确'],
        ];
        $params = array_merge($this->request->get(), $this->request->post());
        $model = DynamicModel::validateData($params, $rules);

        if ($model->hasErrors()) {
            // 验证失败，处理错误
            $errors = $model->errors;
            return $this->asJson([
                'code' => 400,
                'message' => '参数验证失败',
                'errors' => $errors
            ]);
        } else {
            // 验证成功，继续业务逻辑
            return $this->asJson([
                'code' => 200,
                'message' => '验证成功',
                'data' => $model->attributes
            ]);
        }
    }

    /**
     * 大多数验证规则，skipOnError 属性默认为 true，这意味着如果在同一属性上有多个验证器，并且其中一个验证器失败，后续指定skipOnError 为 true 的验证器将被跳过。
     * 但是 只针对当前验证规则有效，对没有skipOnError=true，的规则不受影响
     */
    public function actionSkipError()
    {
        $rules = [
            //定义了两个验证规则，第一个规则必填,报错， 第二个规则是整数，但由于 skipOnError 默认为 true，第二个规则不会被执行
            ['id', 'required', 'message' => 'ID不能为空', ],
            ['id', 'integer', 'message' => 'ID必须是整数', ],

            ['name', 'required', ],
            ['name', 'string', 'min' => 2, 'max' => 5, 'skipOnError' => true],
            ['name', 'match', 'pattern' => '/^[a-z]\w*$/i', 'message' => 'Name包含无效的字符'],

            ['email', 'email', 'message' => '邮箱格式不正确'],
        ];
        $params = array_merge($this->request->get(), $this->request->post());
        $model = DynamicModel::validateData($params, $rules);

        if ($model->hasErrors()) {
            // 验证失败，处理错误
            $errors = $model->errors;
            return $this->asJson([
                'code' => 400,
                'message' => '参数验证失败',
                'errors' => $errors
            ]);
        } else {
            // 验证成功，继续业务逻辑
            return $this->asJson([
                'code' => 200,
                'message' => '验证成功',
                'data' => $model->attributes
            ]);
        }
    }

}